package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.UserLoginVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 42
 * @date 2025/3/28
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private WeChatProperties properties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 用户登录接口
     * @param code
     * @return
     */
    @Override
    public Result<UserLoginVO> login(Map<String,String> codeMap) {

        //1.封装数据，调用wechat接口获取openid
        String code = codeMap.get("code");

        if(StringUtils.isBlank(code)){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("appid", properties.getAppid());
        map.put("secret",properties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        //{"session_key":"pyBdtKsoX3sfyw7UM/Jycg==","openid":"oQCiL7TDsxC8OGpvqSuYWzGeMRCY"}
        String response = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject object = JSON.parseObject(response);
        String openid = (String)object.get("openid");

        if(openid == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        //2.查询用户是否存在
        User user = userMapper.selectByOpenId(openid);
        //2.1不存在，插入用户信息
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //3.为用户下发jwttoken，用于鉴权
        HashMap<String,Object > claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();

        //4.返回信息
        return Result.success(userLoginVO);
    }
}
